package org.springcloud.wisdom.spring_02_classroom.teacher.records.service;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springcloud.wisdom.spring_02_classroom.bean.Page;
import org.springcloud.wisdom.spring_02_classroom.student.attendence.dao.AttendenceDao;
import org.springcloud.wisdom.spring_02_classroom.student.attendence.entity.AttendenceEntity;
import org.springcloud.wisdom.spring_02_classroom.student.sschedule.entity.Student;
import org.springcloud.wisdom.spring_02_classroom.teacher.records.dao.RecordsDao;
import org.springcloud.wisdom.spring_02_classroom.teacher.records.entity.RecordsEntity;
import org.springcloud.wisdom.spring_02_classroom.teacher.tschedule.dao.TeacherScheduleDao;
import org.springcloud.wisdom.spring_02_classroom.websocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class RecordsService {
    @Autowired
    private RecordsDao recordsDao;
    @Autowired
    private TeacherScheduleDao teacherScheduleDao;
    @Autowired
    private AttendenceDao attendenceDao;
    @Autowired
    private WebSocketServer webSocketServer;


    private static final Logger logger = LoggerFactory.getLogger(RecordsService.class);
    // 辅助方法，生成随机签到ID
    private String generateSignId() {
        Random random = new Random();
        return String.valueOf(random.nextInt(900000) + 10000); // 生成10000到99999之间的随机数
    }

    // 辅助方法，获取当前日期和时间，格式化为"yyyy-MM-dd HH:mm:ss"
    private String getCurrentDateTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }

    // 发起签到并处理考勤记录
    public boolean insertRecordsAndAttendence(String tid, String cid) {
        // 获取某门课程的所有学生
        List<Student> students = teacherScheduleDao.selectCourseStudent(tid, cid);
        if (students == null || students.isEmpty()) {
            return false;
        }

        String chour = teacherScheduleDao.selectChourByCid(cid); // 获取课时数

        for (Student student : students) {
            // 为每个学生生成签到记录
            String did = generateSignId();
            String signTime = getCurrentDateTime();
            RecordsEntity recordsEntity = new RecordsEntity();
            recordsEntity.setDid(did);
            recordsEntity.setSid(student.getSid());
            recordsEntity.setStu(false); // 默认 stu 为 false，表示未签到
            recordsEntity.setCid(cid);
            recordsEntity.setTid(tid);
            recordsEntity.setSigntime(signTime);

            // 插入签到记录
            if (recordsDao.insertRecords(recordsEntity) <= 0) {
                return false; // 如果插入失败，则返回 false
            }

            // 检查并可能插入或更新考勤记录
            AttendenceEntity attendence = attendenceDao.selectByCidAndSid(cid, student.getSid());
            if (attendence == null) {
                AttendenceEntity newAttendence = new AttendenceEntity();
                newAttendence.setCid(cid);
                newAttendence.setSid(student.getSid());
                newAttendence.setChour(chour);
                newAttendence.setCount("1");
                newAttendence.setSigncount("0");
                attendenceDao.insertAttendence(newAttendence);
            } else {
                attendence.setCount(String.valueOf(Integer.parseInt(attendence.getCount()) + 1));
                attendenceDao.updateAttendence(attendence);
            }
        }
        Map map = new HashMap<>();
        map.put("cid",cid);
        map.put("content","课程号："+cid);
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
        System.out.println("json"+json);
        return true;
    }

    //签到并更新考勤
    public boolean updateRecordStatus(RecordsEntity recordsEntity) {
        if (recordsEntity == null || recordsEntity.getId() == null) {
            return false;
        }

        try {
            // 更新签到状态
            recordsEntity.setStu(true);
            String reactTime = getCurrentDateTime();
            recordsEntity.setReacttime(reactTime);
            recordsDao.updateRecords(recordsEntity);

            // 获取考勤记录
            AttendenceEntity attendence = attendenceDao.selectByCidAndSid(recordsEntity.getCid(), recordsEntity.getSid());
            logger.info("Before signcount update, attendence: {}", attendence); // 记录更新前的signcount

            if (attendence != null) {
                int signcount = attendence.getSigncount() != null ? Integer.parseInt(attendence.getSigncount()) : 0;
                attendence.setSigncount(String.valueOf(++signcount));
                attendenceDao.updateAttendence(attendence);
                // 再次更新signcount，确保原子性
                attendenceDao.updateSigncountByCidAndSid(recordsEntity.getCid(), recordsEntity.getSid());
            }

            logger.info("After signcount update, attendence: {}", attendence); // 记录更新后的signcount

            return true;
        } catch (Exception e) {
            logger.error("Error updating signcount", e); // 记录异常信息
            return false;
        }
    }

    // 获取签到记录的分页数据
    public Page<RecordsEntity> getAllRecords(int pageNum, int pageSize, String sid) {
        int start = (pageNum - 1) * pageSize;
        List<RecordsEntity> list = recordsDao.get(sid, start, pageSize);
        int total = recordsDao.Counts(sid);
        int pages = (int) (total % pageSize == 0 ? total / pageSize : total / pageSize + 1);
        Page<RecordsEntity> page = new Page<>();
        page.setRecords(list);
        page.setTotal(total);
        page.setPages(pages);
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        return page;
    }
}